package converter;

import java.io.File;
import java.util.regex.Pattern;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;

/**
 * 通过oppenOffice将office文档转换为pdf
 * 对含有图片的ppt转换效果较差
 * @author zhaoxiang
 *
 */
public class Office2PDF {
	private static String officeHome;
	static{
		officeHome = getOfficeHome();
	}
	
	/** jodconverter2.2
	 * 需要先启动openoffice服务
	 * @param sourceFile
	 * @param destFile
	 * @return
	 */
	public static int office2PDF(String sourceFile, String destFile) {  
		File inputFile = new File(sourceFile);
		File outputFile = new File(destFile);
        String OpenOffice_HOME = "D:/openoffice";// 这里是OpenOffice的安装目录,  
        // 假如从文件中读取的URL地址最后一个字符不是 '\'，则添加'\'  
        if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '/') {  
            OpenOffice_HOME += "/";  
        }  
        Process pro = null;  
        try {  
           
/*
            // 启动OpenOffice的服务  
            String command = OpenOffice_HOME  
                    + "program/soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";  
            pro = Runtime.getRuntime().exec(command); 
 */ 
            // connect to an OpenOffice.org instance running on port 8100  
            OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);  
            connection.connect();  
  
            // convert  
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);  
            converter.convert(inputFile, outputFile);  
  
            // close the connection  
            connection.disconnect();  
            // 封闭OpenOffice服务的进程  
//            pro.destroy();  
  
            return 0;  
        } catch (Exception e) {  
            e.printStackTrace();  
            return -1;   
        } finally {  
//            pro.destroy();  
        }  
//        return 1;  
    }  
	
	  /** jodconverter3.0
	 * 将Office文档转换为PDF. 运行该函数需要用到OpenOffice, OpenOffice 
	 *  
	 * @param sourceFile 
	 *            源文件,绝对路径. 可以是Office2003-2007全部格式的文档, Office2010的没测试. 包括.doc, .docx, .xls, .xlsx, .ppt, .pptx等. 
	 *  
	 * @param destFile 
	 *            目标文件.绝对路径. 
	 */  
	public static boolean office2pdf_V2(String inputFilePath) {
	    DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();  
	    config.setOfficeHome(officeHome);  
	    OfficeManager officeManager = config.buildOfficeManager();  
	   try{
	    officeManager.start();
	    OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
	    String outputFilePath = getOutputFilePath(inputFilePath);
	    File inputFile = new File(inputFilePath);
	    if (inputFile.exists()) {// 找不到源文件, 则返回  
	        File outputFile = new File(outputFilePath).getCanonicalFile();  
	        if (!outputFile.getParentFile().exists()) { // 假如目标路径不存在, 则新建该路径  
	            outputFile.getParentFile().mkdirs();  
	        }  
	        converter.convert(inputFile,outputFile);
	    }  
	   }catch(Exception e){
		   e.printStackTrace();
		   return false;
	   }
	    finally{
	    	if(officeManager != null )
	    		officeManager.stop();  
	    }
	    return true;
	}  
	  
	
	public static String getOutputFilePath(String inputFilePath) {
		int index = inputFilePath.lastIndexOf(".");
	    String outputFilePath = inputFilePath.substring(0,index)+".pdf";  
	    return outputFilePath;  
	}  
	
	public static String getOfficeHome() {  
	    String osName = System.getProperty("os.name");  
	    if (Pattern.matches("Linux.*", osName)) {  
	        return "/opt/openoffice4";  
	    } else if (Pattern.matches("Windows.*", osName)) {  
	    	return "D:/openoffice";  
//	    	return "D:/libreOffice4";  
	    } else if (Pattern.matches("Mac.*", osName)) {  
	        return "/Application/OpenOffice.org.app/Contents";  
	    }  
	    return null;  
	}  
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
//		office2pdf_V2("docs/2014.doc");
//		office2pdf_V2("docs/2015.xlsx");
//		office2pdf_V2("docs/2016.ppt");
//		office2pdf_V2("docs/2017.ppt");
		if(args.length > 0){
			String filename = args[0];
			System.out.println("----begin transform "+filename+"----");
			office2pdf_V2(filename);
			System.out.println("----end transform "+filename+"----");
		}
	}

}
